import { defineStore } from "pinia";
import { reactive, computed } from "vue";
// 导出购物车模块
export const useCartStore = defineStore("cart", () => { 
    // 状态
    const cartList = reactive([]);
    
    // 计算属性
    const isConfirmedCart = computed(() => cartList.filter(item => item.isConfirmed));
    
    // 确认订单的总价格
    const confirmedTotalPrice = computed(() => {
        return isConfirmedCart.value.reduce((total, item) => {
            return total + (item.price * item.num); // 直接使用真实价格，不再乘以100
        }, 0);
    });
// 购物车商品总数
    const totalItemsCount = computed(() => {
        return cartList.reduce((total, item) => {
            return total + (item.num || 0);
        }, 0);
    });
// 确认订单商品总数
    const confirmedItemsCount = computed(() => {
        return isConfirmedCart.value.reduce((total, item) => {
            return total + (item.num || 0);
        }, 0);
    });

    // 方法
    // 添加商品到购物车
    const addToCart = (data) => { 
        // 检查商品是否已存在
        const existingItem = cartList.find(item => item.id === data.id);
        // 如果商品已存在，更新数量
        if (existingItem) {
            existingItem.num += data.num || 1;
            return;
        }
        
        // 创建新的购物车商品 增加两个属性为 num(数量)  isConfirmed(确认状态)
        const cartItem = {
            ...data,
            num: data.num || 1,
            isConfirmed: false
        };
        cartList.push(cartItem);
    };
// 更新商品确认状态
    const updateItemConfirmed = (item, confirmed) => {
        const targetItem = cartList.find(cartItem => cartItem.id === item.id);
        if (targetItem) {
            targetItem.isConfirmed = confirmed;
        }
    };
// 切换所有商品确认状态
    const toggleAllConfirmed = (confirmed) => {
        cartList.forEach(item => {
            item.isConfirmed = confirmed;
        });
    };
// 移除已经确认的商品
    const removeConfirmedItems = () => {
        for (let i = cartList.length - 1; i >= 0; i--) {
            if (cartList[i].isConfirmed) {
                cartList.splice(i, 1);
            }
        }
    };
// 移除指定商品
    const removeItemById = (id) => {
        const index = cartList.findIndex(item => item.id === id);
        if (index !== -1) {
            cartList.splice(index, 1);
        }
    };
// 更新商品数量
    const updateItemNum = (id, num) => {
        const item = cartList.find(item => item.id === id);
        if (item && num > 0) {
            item.num = num;
        }
    };

    const clearCart = () => {
        cartList.splice(0, cartList.length);
    };

    return { 
        // 状态
        cartList,
        
        // 计算属性
        isConfirmedCart,
        confirmedTotalPrice,
        totalItemsCount,
        confirmedItemsCount,
        
        // 方法
        addToCart,
        updateItemConfirmed,
        toggleAllConfirmed,
        removeConfirmedItems,
        removeItemById,
        updateItemNum,
        clearCart
    };
});
